package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;
    private final static String KEY_PREFIX = "user:verify:code:";

    @Override
    public Boolean checkDataExist(String data, Integer type) {
        if (type != 1 && type != 2) {
            throw new LyException(400, "输入参数有误");
        }

        Integer count = query().eq(type == 1, "username", data)
                .eq(type == 2, "phone", data).count();
        return count != 0;
    }

    @Override
    public void sendMessage(String phone) {
        //1.校验手机号格式
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(400, "手机号格式错误!");
        }
        //2.生成code
        String code = RandomStringUtils.randomNumeric(6);
        //3.发送短信
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", "13865040091");
        msg.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
        //4. 存入redis
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
    }

    @Override
    public void register(User user, String code) {
        //1.校验验证码是否正确
        String redisCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());

        if (!StringUtils.equals(redisCode, code)) {
            throw new LyException(400, "验证码错误!");
        }
        //TODO 2.校验用户信息

        //3.对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        //4.写入数据库
        save(user);
    }

    @Override
    public UserDTO queryUserByPhoneAndPassword(String username, String password) {
        //1.根据用户名查询用户   因为username带有唯一素引,大型数据库中仍然可以很快查到数据,而密码不可行
        User user = query().eq("username", username).one();

        if (user == null) {
            throw new LyException(400, "用户名或密码错误!");
        }
        //3.校验密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new LyException(400, "用户名或密码错误!");
        }
        UserDTO userDTO = new UserDTO(user);

        return userDTO;
    }
}
